/** https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
 * Tip: Optimizing Performance by Skipping Effects*/

/** === 你可以把effect看做每次render的结果的一部分 === */
/*
有经验的JavaScript开发人员可能会注意到，传递给useEffect的函数在每次呈现时都是不同的。这是故意的。实际上，这让我们可以从效果(effect)中读取count值，而不必担心它会过时。每次我们重新渲染，我们安排一个不同的效果，取代之前的一个。在某种程度上，这使得effects更像是render结果的一部分，每个效果都属于一个特定的render。稍后我们将更清楚地看到为什么这是有用的。

Experienced JavaScript developers might notice that the function passed to useEffect is going to be different on every render. This is intentional. In fact, this is what lets us read the count value from inside the effect without worrying about it getting stale. Every time we re-render, we schedule a different effect, replacing the previous one. In a way, this makes the effects behave more like a part of the render result — each effect “belongs” to a particular render. We will see more clearly why this is useful later on this page.
*/
import React, {useEffect, useState} from 'react';

export default function Counter(){
  const [count1, setCount1] = useState(0);
  const [count2, setCount2] = useState(0);

  /*
    如果您传递一个空数组([]),那么effect中的props和state将始终具有它们的初始值。
    If you pass an empty array ([]), the props and state inside the effect will always have their initial values.
  */
  useEffect(() => {
    setInterval(()=>{
      //你会发现虽然你点击了下面的button改变了count,但是打印出来的永远是最初的那个count
      //同样情况的还有 useCallback ...
      console.log('count1:', count1);
      console.log('count2:', count2);
    },1000)
  },[]);

  return (
    <div>
      <p>count1:{count1}</p>
      <button onClick={() =>
        setCount1(x=>x+1)
      }>count1+</button>

      <p>count2:{count2}</p>
      <button onClick={() =>
        setCount2(x=>x+1)
      }>count2+</button>
    </div>
  );
}
